﻿using AutoMapper;
using PagedList;
using SIG.Infrastructure.Configs;
using SIG.Infrastructure.Helper;
using SIG.InputModel.Admin.Case;
using SIG.Model.Case;
using SIG.Resources.Admin;
using SIG.Service;
using SIG.Service.Case;
using SIG.ViewModel;
using SIG.ViewModel.Admin.Case;
using SIG.WebMVC.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using System.Xml.Linq;

namespace SIG.WebMVC.Areas.Admin.Controllers
{
    [SIGAuth]
    public class ClientController : BaseController
    {
        private readonly IClientService _clientService;
        private readonly IPageMetaService _pageMetaService;
        private readonly IMapper _mapper;

        public ClientController(IClientService clientService, IPageMetaService pageMetaService, IMapper mapper)
        {
            _clientService = clientService;

            _pageMetaService = pageMetaService;
            _mapper = mapper;

        }
        // GET: Admin/Client

        #region Clients

        public ActionResult Index(int? page, string keyword)
        {
            ClientListVM clientListVM = GetElements(page, keyword);
            ViewBag.PageSizes = new SelectList(Site.PageSizes());
            return View(clientListVM);
        }

        private ClientListVM GetElements(int? page, string keyword)
        {
            var specialistListVM = new ClientListVM();

            specialistListVM.Keyword = keyword;
            specialistListVM.PageIndex = (page ?? 1) - 1;
            specialistListVM.PageSize = SettingsManager.Client.PageSize;
            int totalCount;
            var specialistlist = _clientService.GetPagedElements(specialistListVM.PageIndex, specialistListVM.PageSize, specialistListVM.Keyword, out totalCount);
            var specialistVMList = _mapper.Map<List<Client>, List<ClientVM>>(specialistlist);
            specialistListVM.TotalCount = totalCount;
            specialistListVM.Categories = new StaticPagedList<ClientVM>(specialistVMList, specialistListVM.PageIndex + 1, specialistListVM.PageSize, specialistListVM.TotalCount); ;
            return specialistListVM;
        }

        [HttpPost]
        public JsonResult PageSizeSet(int pageSize)
        {
            try
            {
                var xmlFile = Server.MapPath("~/Config/ClientSettings.config");
                XDocument doc = XDocument.Load(xmlFile);

                var item = doc.Descendants("Settings").FirstOrDefault();
                item.Element("PageSize").SetValue(pageSize);
                doc.Save(xmlFile);

                return Json(AR, JsonRequestBehavior.DenyGet);
            }
            catch (Exception ex)
            {
                AR.Setfailure(ex.Message);
                return Json(AR, JsonRequestBehavior.DenyGet);
            }
        }

        [HttpGet]
        public ActionResult Add()
        {
            var vClient = new ClientIM();
            vClient.Active = true;
            vClient.Importance = 0;

            return PartialView("_Add", vClient);
        }



        [HttpPost]
        public JsonResult Add(ClientIM vm)
        {

            if (!ModelState.IsValid)
            {
                AR.Setfailure(GetModelErrorMessage());
                return Json(AR, JsonRequestBehavior.DenyGet);
            }

            var newClient = _mapper.Map<ClientIM, Client>(vm);
            _clientService.Create(newClient);
          

            int count;
            var pageSize = SettingsManager.Client.PageSize;
            var list = _clientService.GetPagedElements(0, pageSize, string.Empty, out count);
            List<ClientVM> categories = _mapper.Map<List<Client>, List<ClientVM>>(list);
            AR.Data = RenderPartialViewToString("_ClientList", categories);
      
            AR.SetSuccess(String.Format(Messages.AlertCreateSuccess, EntityNames.Client));
            return Json(AR, JsonRequestBehavior.DenyGet);

        }


        [HttpGet]
        public ActionResult Edit(int id)
        {

            Client client = _clientService.GetById(id);
            if (client == null)
            {
                AR.Setfailure(Messages.HttpNotFound);
                return Json(AR, JsonRequestBehavior.AllowGet);
            }

            var vm = _mapper.Map<ClientIM>(client);

            return PartialView("_Edit", vm);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]

        public JsonResult Edit(ClientIM vm)
        {

            if (!ModelState.IsValid)
            {
                AR.Setfailure(GetModelErrorMessage());
                return Json(AR, JsonRequestBehavior.DenyGet);
            }
            var newClient = _mapper.Map<ClientIM, Client>(vm);
            _clientService.Update(newClient);

           

            var client = _mapper.Map<ClientVM>(newClient);
            AR.Id = client.Id;
            AR.Data = RenderPartialViewToString("_ClientItem", client);

            AR.SetSuccess(String.Format(Messages.AlertUpdateSuccess, EntityNames.Client));
            return Json(AR, JsonRequestBehavior.DenyGet);

        }

        // DELETE: /User/DeleteSite
        [HttpPost]
        [ValidateAntiForgeryToken]
        public JsonResult Delete(int id)
        {

            Client vClient = _clientService.GetByIdWithWorks(id);

            if (vClient.Works.Any())
            {
                AR.Setfailure(string.Format(Messages.HasChildCanNotDelete,EntityNames.Client,EntityNames.Work));
                return Json(AR, JsonRequestBehavior.DenyGet);
            }

            _clientService.Delete(vClient);
            AR.SetSuccess(String.Format(Messages.AlertDeleteSuccess, EntityNames.Client));
            return Json(AR, JsonRequestBehavior.DenyGet);

        }


        [HttpPost]
        [ValidateAntiForgeryToken]
        public JsonResult IsActive(int id)
        {

            var vClient = _clientService.GetById(id);
            if (vClient == null)
            {
                AR.Setfailure(Messages.HttpNotFound);
                return Json(AR, JsonRequestBehavior.DenyGet);
            }

            try
            {
                vClient.Active = !vClient.Active;
                _clientService.Update(vClient);
                var vm = _mapper.Map<ClientVM>(vClient);

                AR.Data = RenderPartialViewToString("_ClientItem", vm);
                AR.SetSuccess(String.Format(Messages.AlertUpdateSuccess, EntityNames.Client));
                return Json(AR, JsonRequestBehavior.DenyGet);
            }
            catch (Exception ex)
            {
                AR.Setfailure(ex.Message);
                return Json(AR, JsonRequestBehavior.DenyGet);
            }
        }

        


        //[AllowAnonymous]
        //public JsonResult IsSeoNameUnique(string seoName, int? Id)
        //{
        //    return !IsExist(seoName, Id)
        //        ? Json(true, JsonRequestBehavior.AllowGet)
        //        : Json(false, JsonRequestBehavior.AllowGet);
        //}
        //[AllowAnonymous]
        //public bool IsExist(string seoName, int? id)
        //{
        //    var wType = _clientService.GetAll().Where(w => w.SeoName == seoName);
        //    if (id > 0)
        //    {
        //        wType = wType.Where(w => w.Id != id);
        //    }

        //    if (wType.Count() > 0)
        //        return true;

        //    return false;
        //}



        #endregion
    }
}